/**
 * 收藏管理工具
 */

// 检查是否已登录
function checkLogin() {
  const token = uni.getStorageSync('uni_id_token')
  
  if (!token) {
    return false
  }
  
  const tokenExpired = Number(uni.getStorageSync('uni_id_token_expired') || 0)
  const now = Date.now()
  
  return tokenExpired > now
}

// 跳转到登录页
function goToLogin() {
  uni.showModal({
    title: '需要登录',
    content: '收藏功能需要登录后使用，是否前往登录？',
    success: (res) => {
      if (res.confirm) {
        uni.navigateTo({
          url: '/uni_modules/uni-id-pages/pages/login/login-withpwd'
        })
      }
    }
  })
}

// 添加收藏
export async function addFavorite(dish) {
  // 检查登录状态
  if (!checkLogin()) {
    goToLogin()
    return {
      success: false,
      message: '请先登录'
    }
  }
  
  try {
    // 获取 uid 的多种方式
    let uid = null
    
    // 方式1: 尝试从 uniCloud 获取
    try {
      const userInfo = uniCloud.getCurrentUserInfo()
      if (userInfo && userInfo.uid) {
        uid = userInfo.uid
      }
    } catch (e) {
      // uniCloud.getCurrentUserInfo 失败，继续尝试其他方式
    }
    
    // 方式2: 如果没有获取到，从本地存储获取
    if (!uid) {
      try {
        const userInfoStr = uni.getStorageSync('uni_id_user_info')
        if (userInfoStr) {
          const userInfo = typeof userInfoStr === 'string' ? JSON.parse(userInfoStr) : userInfoStr
          uid = userInfo._id || userInfo.uid
        }
      } catch (e) {
        // 从本地存储获取 uid 失败
      }
    }
    
    if (!uid) {
      goToLogin()
      return {
        success: false,
        message: '请先登录'
      }
    }
    
    const res = await uniCloud.callFunction({
      name: 'food-favorites',
      data: {
        action: 'add-favorite',
        data: {
          uid,
          dish_id: dish._id || dish.id,
          dish_name: dish.name,
          dish_image: dish.image,
          dish_price: dish.price || 0,
          dish_spiciness: dish.spiciness || 0,
          category_id: dish.category_id || dish.categoryId || '',
          category_name: dish.category_name || dish.categoryName || ''
        }
      }
    })

    if (res.result && res.result.code === 200) {
      return {
        success: true,
        message: '收藏成功',
        favorite_id: res.result.data?.favorite_id
      }
    } else if (res.result && res.result.code === 401) {
      goToLogin()
      return {
        success: false,
        message: '请先登录'
      }
    } else {
      return {
        success: false,
        message: res.result?.message || '收藏失败'
      }
    }
  } catch (err) {
    return {
      success: false,
      message: '收藏失败'
    }
  }
}

// 删除收藏
export async function removeFavorite(favoriteId) {
  // 检查登录状态
  if (!checkLogin()) {
    goToLogin()
    return {
      success: false,
      message: '请先登录'
    }
  }
  
  try {
    const res = await uniCloud.callFunction({
      name: 'food-favorites',
      data: {
        action: 'remove-favorite',
        data: {
          favorite_id: favoriteId
        }
      }
    })

    if (res.result && res.result.code === 200) {
      return {
        success: true,
        message: '已取消收藏'
      }
    } else if (res.result && res.result.code === 401) {
      goToLogin()
      return {
        success: false,
        message: '请先登录'
      }
    } else {
      return {
        success: false,
        message: res.result?.message || '取消收藏失败'
      }
    }
  } catch (err) {
    return {
      success: false,
      message: '取消收藏失败'
    }
  }
}

// 检查是否已收藏
export async function checkFavorite(dishId) {
  // 未登录时直接返回未收藏状态，不弹窗
  if (!checkLogin()) {
    return {
      success: true,
      isFavorite: false,
      favorite_id: null
    }
  }
  
  try {
    // 获取 uid
    let uid = null
    try {
      const userInfo = uniCloud.getCurrentUserInfo()
      if (userInfo && userInfo.uid) {
        uid = userInfo.uid
      }
    } catch (e) {
      // 尝试从本地存储获取
      try {
        const userInfoStr = uni.getStorageSync('uni_id_user_info')
        if (userInfoStr) {
          const userInfo = typeof userInfoStr === 'string' ? JSON.parse(userInfoStr) : userInfoStr
          uid = userInfo._id || userInfo.uid
        }
      } catch (e2) {
        // 都失败了
      }
    }
    
    if (!uid) {
      return {
        success: true,
        isFavorite: false,
        favorite_id: null
      }
    }
    
    const res = await uniCloud.callFunction({
      name: 'food-favorites',
      data: {
        action: 'check-favorite',
        data: {
          uid,
          dish_id: dishId
        }
      }
    })

    if (res.result && res.result.code === 200) {
      return {
        success: true,
        isFavorite: res.result.data?.isFavorite || false,
        favorite_id: res.result.data?.favorite_id || null
      }
    } else {
      return {
        success: false,
        isFavorite: false,
        favorite_id: null
      }
    }
  } catch (err) {
    return {
      success: false,
      isFavorite: false,
      favorite_id: null
    }
  }
}

// 批量检查收藏状态
export async function batchCheckFavorites(dishIds) {
  // 未登录时直接返回空对象，不进行网络请求
  if (!checkLogin()) {
    const favoriteMap = {}
    dishIds.forEach(id => {
      favoriteMap[id] = {
        isFavorite: false,
        favorite_id: null
      }
    })
    return favoriteMap
  }
  
  try {
    const promises = dishIds.map(id => checkFavorite(id))
    const results = await Promise.all(promises)
    
    const favoriteMap = {}
    dishIds.forEach((id, index) => {
      favoriteMap[id] = {
        isFavorite: results[index].isFavorite,
        favorite_id: results[index].favorite_id
      }
    })
    
    return favoriteMap
  } catch (err) {
    return {}
  }
}

export default {
  addFavorite,
  removeFavorite,
  checkFavorite,
  batchCheckFavorites
}

